// Package repository
// Created by GoLand
// @User: lenora
// @Date: 2023/11/29
// @Time: 18:27

package repository

import (
	"camp-homework/week02/internal/domain"
	"camp-homework/week02/internal/repository/dao"
	"context"
	"github.com/gin-gonic/gin"
)

var (
	ErrDuplicateUser = dao.ErrDuplicateUser
	ErrUserNotFound  = dao.ErrRecordNotFound
)

type UserRepository struct {
	dao *dao.UserDAO
}

func NewUserRepository(dao *dao.UserDAO) *UserRepository {
	return &UserRepository{dao: dao}
}

func (repo *UserRepository) Create(ctx context.Context, u domain.UserBase) error {
	return repo.dao.Insert(ctx, dao.User{
		UserName: u.UserName,
		Password: u.Password,
	})
}

func (repo *UserRepository) FindByName(ctx context.Context, name string) (domain.UserBase, error) {
	u, err := repo.dao.FindByName(ctx, name)
	if err != nil {
		return domain.UserBase{}, err
	}

	user := domain.UserBase{
		Id:       u.Id,
		UserName: u.UserName,
		Password: u.Password,
	}
	return user, nil
}

func (repo *UserRepository) Profile(ctx context.Context, uid uint64) (domain.User, error) {
	u, err := repo.dao.FindById(ctx, uid)
	if err != nil {
		return domain.User{}, err
	}
	return repo.toDomain(u), nil
}

func (repo *UserRepository) Edit(ctx *gin.Context, uid uint64, nickname, birth, desc string) error {
	return repo.dao.UpdateById(ctx, dao.User{
		Id:       uid,
		Nickname: nickname,
		Birth:    birth,
		Desc:     desc,
	})
}

func (repo *UserRepository) toDomain(u dao.User) domain.User {
	return domain.User{
		Id:       u.Id,
		UserName: u.UserName,
		Nickname: u.Nickname,
		Birth:    u.Birth,
		Desc:     u.Desc,
	}
}
